#include <iostream>
#include <string>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <pthread.h>
#include "Terminal.hpp"

using namespace std;

struct ThreadData
{
    int sockfd;
    struct sockaddr_in server;
};

void* recv_message(void* args)
{
    OpenTerminal();
    ThreadData* ptd = (ThreadData*)args;
    char buffer[1024] = {0};
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t templen = sizeof(temp);
        ssize_t s = recvfrom(ptd->sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &templen);
        if(s < 0)
        {
            cerr << "recvfrom error" << strerror(errno) << endl;
        }
        if(s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}

void* send_message(void* args)
{
    ThreadData* ptd = (ThreadData*)args;
    string message;
    char buffer[1024] = {0};
    while(true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);

        socklen_t len = sizeof(ptd->server);
        ssize_t n = sendto(ptd->sockfd, message.c_str(), message.size(), 0, (sockaddr*)&ptd->server, len);
        if(n < 0)
        {
            cout << "sendto error" << strerror(errno) << endl;
        }
    }
}

// ./client sip sport
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        cout << "Usage: " << argv[0] << " serverip serverport" << endl;
        exit(0);
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "socket create fail" << endl;
        return 1;
    }
    uint16_t port = stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t len = sizeof(server);

    ThreadData td;
    td.sockfd = sockfd;
    td.server = server;

    // 创建多线程
    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);
    

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    close(sockfd);

    return 0;
}